package com.cjz.rxjavalearn;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class MainActivity extends Activity {

    private TextView tv;
    Subscriber<Integer> subscriber;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        tv = (TextView) findViewById(R.id.tv);
        tv.setOnClickListener(view -> Log.e("cjz", "text view is clicked!"));


        testDemo1();
        testDemo2();
    }

    private void testDemo2() {
        Observable
                .create((Subscriber<? super Integer> sub) -> {
                    for (int i = 0; i < 10; i++) {
                        sub.onNext(i);
                    }
                    sub.onCompleted();
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .onBackpressureBuffer()
                .subscribe(integer -> tv.setText(tv.getText() + "" + integer + "\n"));
    }

    private void testDemo1() {
        //创建被观察对象

        Observable<Integer> observable = Observable.create(new Observable.OnSubscribe<Integer>() {
            @Override
            public void call(Subscriber<? super Integer> subscriber) {
                for (int i = 0; i < 10; i++) {
                    System.out.println("OnSubscribe call() thread id " + Thread.currentThread().getId() + " " + i);
                    if (!subscriber.isUnsubscribed()) {
                        subscriber.onNext(i);
                    }
                }
                if (!subscriber.isUnsubscribed()) {
                    subscriber.onCompleted();
                }
            }
        });

        //创建订阅者
        Subscriber<Integer> subscriber = new Subscriber<Integer>() {
            @Override
            public void onCompleted() {

                System.out.println("Subscriber call() thread id " + Thread.currentThread().getId() + " downloaded !");
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(Integer integer) {
                System.out.println("Subscriber call() thread id " + Thread.currentThread().getId() + " current download progress " + integer);
            }
        };

        //指定线程环境
        observable = observable.subscribeOn(Schedulers.newThread());
        observable = observable.observeOn(AndroidSchedulers.mainThread());

        //桥接被观察对象与订阅者
        observable.subscribe(subscriber);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (subscriber != null && !subscriber.isUnsubscribed()) {
            subscriber.unsubscribe();
        }
    }
}
